// 企业服务类
package org.example.backend.service;

import org.example.backend.dto.CompanyDto;
import org.example.backend.dto.CompanyReviewDto;
import org.example.backend.entity.Company;
import org.example.backend.entity.User;
import org.example.backend.exception.BusinessException;
import org.example.backend.exception.ResourceNotFoundException;
import org.example.backend.repository.CompanyRepository;
import org.example.backend.repository.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CompanyService {

    private final CompanyRepository companyRepository;
    private final UserRepository userRepository;

    public CompanyService(CompanyRepository companyRepository, UserRepository userRepository) {
        this.companyRepository = companyRepository;
        this.userRepository = userRepository;
    }

    /**
     * 创建企业信息
     */
    public Company createCompany(CompanyDto companyDto, Long userId) {
        // 检查统一社会信用代码是否已存在
        if (companyRepository.findByUnifiedCode(companyDto.getUnifiedCode()).isPresent()) {
            throw new BusinessException("统一社会信用代码已存在");
        }

        // 检查企业名称是否已存在
        if (companyRepository.findByName(companyDto.getName()).isPresent()) {
            throw new BusinessException("企业名称已存在");
        }

        // 检查用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("用户不存在"));

        // 检查是否已有关联的企业信息
        if (companyRepository.findByUserId(userId).isPresent()) {
            throw new BusinessException("该用户已有关联的企业信息");
        }

        Company company = new Company();
        company.setUserId(userId);
        company.setName(companyDto.getName());
        company.setUnifiedCode(companyDto.getUnifiedCode());
        company.setLegalPerson(companyDto.getLegalPerson());
        company.setRegisteredCapital(companyDto.getRegisteredCapital());
        company.setEstablishmentDate(companyDto.getEstablishmentDate());
        company.setBusinessScope(companyDto.getBusinessScope());
        company.setAddress(companyDto.getAddress());
        company.setContactPerson(companyDto.getContactPerson());
        company.setContactPhone(companyDto.getContactPhone());
        company.setContactEmail(companyDto.getContactEmail());
        company.setWebsite(companyDto.getWebsite());
        company.setIntroduction(companyDto.getIntroduction());
        company.setLogo(companyDto.getLogo());
        company.setStatus(0); // 默认待审核状态

        return companyRepository.save(company);
    }

    /**
     * 更新企业信息
     */
    public Company updateCompany(Long companyId, CompanyDto companyDto) {
        Company company = companyRepository.findById(companyId)
                .orElseThrow(() -> new ResourceNotFoundException("企业信息不存在"));

        // 检查统一社会信用代码是否已被其他企业使用
        Company existingCompany = companyRepository.findByUnifiedCode(companyDto.getUnifiedCode()).orElse(null);
        if (existingCompany != null && !existingCompany.getId().equals(companyId)) {
            throw new BusinessException("统一社会信用代码已存在");
        }

        // 检查企业名称是否已被其他企业使用
        existingCompany = companyRepository.findByName(companyDto.getName()).orElse(null);
        if (existingCompany != null && !existingCompany.getId().equals(companyId)) {
            throw new BusinessException("企业名称已存在");
        }

        company.setName(companyDto.getName());
        company.setUnifiedCode(companyDto.getUnifiedCode());
        company.setLegalPerson(companyDto.getLegalPerson());
        company.setRegisteredCapital(companyDto.getRegisteredCapital());
        company.setEstablishmentDate(companyDto.getEstablishmentDate());
        company.setBusinessScope(companyDto.getBusinessScope());
        company.setAddress(companyDto.getAddress());
        company.setContactPerson(companyDto.getContactPerson());
        company.setContactPhone(companyDto.getContactPhone());
        company.setContactEmail(companyDto.getContactEmail());
        company.setWebsite(companyDto.getWebsite());
        company.setIntroduction(companyDto.getIntroduction());
        company.setLogo(companyDto.getLogo());

        return companyRepository.save(company);
    }

    /**
     * 获取企业信息
     */
    @Transactional(readOnly = true)
    public Company getCompanyByUserId(Long userId) {
        return companyRepository.findByUserId(userId)
                .orElseThrow(() -> new ResourceNotFoundException("企业信息不存在"));
    }

    /**
     * 获取企业信息
     */
    @Transactional(readOnly = true)
    public Company getCompanyById(Long companyId) {
        return companyRepository.findById(companyId)
                .orElseThrow(() -> new ResourceNotFoundException("企业信息不存在"));
    }

    /**
     * 提交企业审核
     */
    public Company submitForReview(Long companyId) {
        Company company = companyRepository.findById(companyId)
                .orElseThrow(() -> new ResourceNotFoundException("企业信息不存在"));

        // 设置为待审核状态
        company.setStatus(0);
        return companyRepository.save(company);
    }

    /**
     * 审核企业信息
     */
    public Company reviewCompany(Long companyId, CompanyReviewDto reviewDto) {
        Company company = companyRepository.findById(companyId)
                .orElseThrow(() -> new ResourceNotFoundException("企业信息不存在"));

        // 只能审核状态为待审核的企业
        if (company.getStatus() != 0) {
            throw new BusinessException("企业状态不正确，无法审核");
        }

        company.setStatus(reviewDto.getStatus());
        if (reviewDto.getStatus() == 2 && reviewDto.getRejectReason() != null) {
            company.setRejectReason(reviewDto.getRejectReason());
        }

        return companyRepository.save(company);
    }

    /**
     * 管理员更新企业信息
     */
    public Company updateCompanyByAdmin(Long userId, CompanyDto companyDto) {
        Company company = companyRepository.findByUserId(userId)
                .orElseThrow(() -> new ResourceNotFoundException("企业信息不存在"));

        // 检查统一社会信用代码是否已被其他企业使用
        Company existingCompany = companyRepository.findByUnifiedCode(companyDto.getUnifiedCode()).orElse(null);
        if (existingCompany != null && !existingCompany.getId().equals(company.getId())) {
            throw new BusinessException("统一社会信用代码已存在");
        }

        // 检查企业名称是否已被其他企业使用
        existingCompany = companyRepository.findByName(companyDto.getName()).orElse(null);
        if (existingCompany != null && !existingCompany.getId().equals(company.getId())) {
            throw new BusinessException("企业名称已存在");
        }

        company.setName(companyDto.getName());
        company.setUnifiedCode(companyDto.getUnifiedCode());
        company.setLegalPerson(companyDto.getLegalPerson());
        company.setRegisteredCapital(companyDto.getRegisteredCapital());
        company.setEstablishmentDate(companyDto.getEstablishmentDate());
        company.setBusinessScope(companyDto.getBusinessScope());
        company.setAddress(companyDto.getAddress());
        company.setContactPerson(companyDto.getContactPerson());
        company.setContactPhone(companyDto.getContactPhone());
        company.setContactEmail(companyDto.getContactEmail());
        company.setWebsite(companyDto.getWebsite());
        company.setIntroduction(companyDto.getIntroduction());
        company.setLogo(companyDto.getLogo());

        return companyRepository.save(company);
    }

}
